package com.tiantian.lianhui.admin.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.tiantian.lianhui.admin.domain.dto.req.UserLoginReqDTO;
import com.tiantian.lianhui.admin.domain.dto.req.UserRegisterReqDTO;
import com.tiantian.lianhui.admin.domain.dto.req.UserUpdateReqDTO;
import com.tiantian.lianhui.admin.domain.dto.resp.UserLoginRespDTO;
import com.tiantian.lianhui.admin.domain.dto.resp.UserRespDTO;
import com.tiantian.lianhui.admin.domain.entity.UserEntity;
import com.tiantian.lianhui.admin.mapper.UserMapper;
import com.tiantian.lianhui.admin.service.GroupService;
import com.tiantian.lianhui.admin.service.UserService;
import com.tiantian.lianhui.common.biz.user.UserContext;
import com.tiantian.lianhui.common.convention.exception.ClientException;
import com.tiantian.lianhui.common.convention.exception.ServiceException;
import lombok.RequiredArgsConstructor;
import org.redisson.api.RBloomFilter;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;

import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

import static com.tiantian.lianhui.common.constant.RedisCacheConstant.LOCK_USER_REGISTER_KEY;
import static com.tiantian.lianhui.common.constant.RedisCacheConstant.USER_LOGIN_KEY;
import static com.tiantian.lianhui.common.constant.UserConstant.TOKEN_RENEWAL_TIME;
import static com.tiantian.lianhui.common.enums.UserErrorCodeEnum.*;

/**
 * @author tiantian
 */
@Service
@RequiredArgsConstructor
public class UserServiceImpl implements UserService {

    private final UserMapper userMapper;
    private final GroupService groupService;
    private final RBloomFilter<String> userRegisterCachePenetrationBloomFilter;
    private final RedissonClient redissonClient;
    private final StringRedisTemplate stringRedisTemplate;
    private final PlatformTransactionManager transactionManager;


    @Override
    public UserRespDTO getUserByUsername(String username) {
        LambdaQueryWrapper<UserEntity> queryWrapper = Wrappers.lambdaQuery(UserEntity.class)
                .eq(UserEntity::getUsername, username);
        UserEntity userEntity = userMapper.selectOne(queryWrapper);
        if (userEntity == null) {
            throw new ServiceException(USER_NULL);
        }
        return BeanUtil.copyProperties(userEntity, UserRespDTO.class);
    }

    @Override
    public Boolean availableUsername(String username) {
        return !userRegisterCachePenetrationBloomFilter.contains(username);
    }

    @Override
    public void register(UserRegisterReqDTO requestParam) {
        if (!availableUsername(requestParam.getUsername())) {
            throw new ClientException(USER_NAME_EXIST);
        }
        RLock lock = redissonClient.getLock(LOCK_USER_REGISTER_KEY + requestParam.getUsername());
        if (!lock.tryLock()) {
            // 获取不到锁, 快速失败
            throw new ClientException(USER_NAME_EXIST);
        }
        TransactionStatus status = transactionManager.getTransaction(new DefaultTransactionDefinition());
        try {
            int inserted = userMapper.insert(BeanUtil.toBean(requestParam, UserEntity.class));
            if (inserted < 1) {
                throw new ClientException(USER_SAVE_ERROR);
            }
            groupService.saveGroup(requestParam.getUsername(), "默认分组");
            transactionManager.commit(status);
        } catch (DuplicateKeyException ex) {
            transactionManager.rollback(status);
            throw new ClientException(USER_EXIST);
        } finally {
            lock.unlock();
        }
        userRegisterCachePenetrationBloomFilter.add(requestParam.getUsername());
    }

    @Override
    public void update(UserUpdateReqDTO requestParam) {
        if (!Objects.equals(requestParam.getUsername(), UserContext.getUsername())) {
            throw new ClientException("当前登录用户修改请求异常");
        }
        LambdaUpdateWrapper<UserEntity> updateWrapper = Wrappers.lambdaUpdate(UserEntity.class)
                .eq(UserEntity::getUsername, requestParam.getUsername());
        userMapper.update(BeanUtil.toBean(requestParam, UserEntity.class), updateWrapper);
    }

    @Override
    public UserLoginRespDTO login(UserLoginReqDTO requestParam) {
        LambdaQueryWrapper<UserEntity> queryWrapper = Wrappers.lambdaQuery(UserEntity.class)
                .eq(UserEntity::getUsername, requestParam.getUsername())
                .eq(UserEntity::getPassword, requestParam.getPassword())
                .eq(UserEntity::getDelFlag, 0);
        UserEntity userEntity = userMapper.selectOne(queryWrapper);
        if (userEntity == null) {
            throw new ClientException("用户不存在");
        }
        // 判断token合法性并对token进行续期
        Map<Object, Object> hasLoginMap = stringRedisTemplate.opsForHash().entries(USER_LOGIN_KEY + requestParam.getUsername());
        if (CollUtil.isNotEmpty(hasLoginMap)) {
            stringRedisTemplate.expire(USER_LOGIN_KEY + requestParam.getUsername(), TOKEN_RENEWAL_TIME, TimeUnit.SECONDS);
            String token = hasLoginMap.keySet().stream()
                    .findFirst()
                    .map(Object::toString)
                    .orElseThrow(() -> new ClientException("用户登录错误"));
            return new UserLoginRespDTO(token);
        }
        /*
         * Hash
         * Key：login_用户名
         * Value：
         *  Key：token标识
         *  Val：JSON 字符串（用户信息）
         */
        String uuid = IdUtil.fastSimpleUUID();
        String key = USER_LOGIN_KEY + requestParam.getUsername();
        String value = JSON.toJSONString(userEntity);
        stringRedisTemplate.opsForHash().put(key, uuid, value);
        stringRedisTemplate.expire(key, TOKEN_RENEWAL_TIME, TimeUnit.SECONDS);
        return new UserLoginRespDTO(uuid);
    }

    @Override
    public Boolean checkLogin(String username, String token) {
        return stringRedisTemplate.opsForHash().get(USER_LOGIN_KEY + username, token) != null;
    }

    @Override
    public void logout(String username, String token) {
        if (checkLogin(username, token)) {
            stringRedisTemplate.delete(USER_LOGIN_KEY + username);
            return;
        }
        throw new ClientException("用户Token不存在或用户未登录");
    }
}
